# ai_helper.py

import re
from abc import ABC, abstractmethod

class AIHelper(ABC):
    """AI助手基类"""

    def __init__(self, id, name, type, version, is_online, score):
        self.id = id
        self.name = name
        self.type = type
        self.version = version
        self.is_online = is_online
        self.score = score

    def __str__(self):
        status = "🟢在线" if self.is_online else "🔴离线"
        return f"ID: {self.id}, 名称: {self.name}, 类型: {self.type}, 版本: {self.version}, 状态: {status}, 能力评分: {self.score} [{self.type}]"

    # Getters and Setters
    def get_id(self):
        return self.id

    def set_id(self, id):
        self.id = id

    def get_name(self):
        return self.name

    def set_name(self, name):
        self.name = name

    def get_type(self):
        return self.type

    def set_type(self, type):
        self.type = type

    def get_version(self):
        return self.version

    def set_version(self, version):
        self.version = version

    def is_online_status(self):
        return self.is_online

    def set_online(self, is_online):
        self.is_online = is_online

    def get_score(self):
        return self.score

    def set_score(self, score):
        self.score = score


class TextHelper(AIHelper):
    """文本助手类，继承自AIHelper"""

    def __init__(self, id, name, version, is_online, score, language_support):
        super().__init__(id, name, "文本助手", version, is_online, score)
        self.language_support = language_support

    def __str__(self):
        return super().__str__() + f" [语言支持: {self.language_support}]"

    # Getters and Setters
    def get_language_support(self):
        return self.language_support

    def set_language_support(self, language_support):
        self.language_support = language_support


class ImageHelper(AIHelper):
    """图像助手类，继承自AIHelper"""

    def __init__(self, id, name, version, is_online, score, image_formats):
        super().__init__(id, name, "图像助手", version, is_online, score)
        self.image_formats = image_formats  # 支持的图像格式列表

    def __str__(self):
        return super().__str__() + f" [支持格式: {', '.join(self.image_formats)}]"

    # Getters and Setters
    def get_image_formats(self):
        return self.image_formats

    def set_image_formats(self, image_formats):
        self.image_formats = image_formats


class AIManager:
    """AI助手管理器"""

    def __init__(self):
        self.assistants = [None] * 10  # 固定大小数组存储助手信息
        self.scanner = None  # Python中使用input()替代Scanner

    def menu(self):
        while True:
            print("\n========== 🤖AI助手管理器 ==========")
            print("1. 查看所有AI助手列表")
            print("2. 根据ID查询助手详情")
            print("3. 添加新的AI助手")
            print("4. 根据ID修改助手信息")
            print("5. 删除AI助手（按ID）")
            print("6. 启动AI助手服务")
            print("7. 停止AI助手服务")
            print("8. 为AI助手分配任务")
            print("9. 显示系统统计信息")
            print("0. 退出系统")
            print("===================================")
            try:
                choice = int(input("请选择操作: "))
                if choice == 1:
                    self.show_all_assistants()
                elif choice == 2:
                    self.query_assistant_by_id()
                elif choice == 3:
                    self.add_assistant()
                elif choice == 4:
                    self.modify_assistant()
                elif choice == 5:
                    self.delete_assistant()
                elif choice == 6:
                    self.start_assistant()
                elif choice == 7:
                    self.stop_assistant()
                elif choice == 8:
                    self.assign_task()
                elif choice == 9:
                    self.show_statistics()
                elif choice == 0:
                    print("感谢使用AI助手管理系统！")
                    break
                else:
                    print("❌ 请输入有效的选项数字 (0-9)")
            except ValueError:
                print("❌ 输入格式错误，请输入数字选项")

    def show_all_assistants(self):
        """查看所有AI助手列表"""
        print("所有AI助手列表：")
        has_assistant = False
        for i, assistant in enumerate(self.assistants):
            if assistant is not None:
                print(f"{i + 1}. {assistant}")
                has_assistant = True
        if not has_assistant:
            print("你还未添加任何AI助手哟，请先添加！")

    def query_assistant_by_id(self):
        """根据ID查询助手详情"""
        try:
            id = int(input("请输入要查询的AI助手ID: "))
            for assistant in self.assistants:
                if assistant is not None and assistant.get_id() == id:
                    print(f"✅ 查询结果: {assistant}")
                    return
            print(f"❌ 未找到ID为 {id} 的助手")
        except ValueError:
            print("❌ ID格式错误，请输入数字")

    def is_valid_version(self, version):
        """验证版本号格式 (x.x.x)"""
        pattern = r"^\d+\.\d+\.\d+$"
        return re.match(pattern, version) is not None

    def add_assistant(self):
        """添加新的AI助手"""
        print("添加新AI助手")

        # 输入并验证ID
        while True:
            try:
                id = int(input("请输入ID: "))
                if id <= 0:
                    print("❌ ID必须为正整数，请重新输入")
                    continue

                # 检查ID是否已存在
                id_exists = False
                for assistant in self.assistants:
                    if assistant is not None and assistant.get_id() == id:
                        print("❌ ID已存在，请重新输入ID")
                        id_exists = True
                        break

                if not id_exists:
                    break
            except ValueError:
                print("❌ ID格式错误，请输入数字")

        name = input("请输入名称: ")

        # 输入并验证版本号
        while True:
            version = input("请输入版本号 (格式: x.x.x): ")
            if self.is_valid_version(version):
                break
            else:
                print("❌ 版本号格式不正确，请使用 x.x.x 格式 (如: 1.0.0)")

        # 输入并验证在线状态
        while True:
            try:
                online_input = int(input("是否在线？(1-是, 0-否): "))
                if online_input in [0, 1]:
                    is_online = bool(online_input)
                    break
                else:
                    print("❌ 请输入 1 或 0")
            except ValueError:
                print("❌ 输入格式错误，请输入 1 或 0")

        # 输入并验证能力评分
        while True:
            try:
                score = int(input("请输入能力评分(0-100): "))
                if 0 <= score <= 100:
                    break
                else:
                    print("❌ 能力评分应在0-100之间")
            except ValueError:
                print("❌ 评分格式错误，请输入数字")

        # 选择助手类型
        print("请选择助手类型:")
        print("1. 文本助手")
        print("2. 图像助手")

        while True:
            try:
                assistant_type = int(input("请选择助手类型 (1-2): "))
                if assistant_type == 1:
                    language_support = input("请输入支持的语言 (如: 中文,英文): ")
                    assistant = TextHelper(id, name, version, is_online, score, language_support)
                    break
                elif assistant_type == 2:
                    formats = input("请输入支持的图像格式，用逗号分隔 (如: jpg,png,gif): ").split(',')
                    formats = [f.strip() for f in formats]
                    assistant = ImageHelper(id, name, version, is_online, score, formats)
                    break
                else:
                    print("❌ 请输入有效的选项 (1-2)")
            except ValueError:
                print("❌ 输入格式错误，请输入数字")

        # 添加到助手列表
        for i in range(len(self.assistants)):
            if self.assistants[i] is None:
                self.assistants[i] = assistant
                print(f"✅ 助手【{name}】添加成功！")
                return

        print("❌ 助手列表已满，无法添加")

    def modify_assistant(self):
        """根据ID修改助手信息"""
        print("修改AI助手数据")

        try:
            id = int(input("请输入ID: "))
        except ValueError:
            print("❌ ID格式错误，请输入数字")
            return

        for i in range(len(self.assistants)):
            if self.assistants[i] is not None and self.assistants[i].get_id() == id:
                print("可修改属性列表为：name,type,version,is_online,score")
                attribute = input("请输入要修改的属性: ").lower()
                value = input("请输入要修改的值: ")

                try:
                    if attribute == "name":
                        self.assistants[i].set_name(value)
                    elif attribute == "type":
                        self.assistants[i].set_type(value)
                    elif attribute == "version":
                        if self.is_valid_version(value):
                            self.assistants[i].set_version(value)
                        else:
                            print("❌ 版本号格式不正确，请使用 x.x.x 格式 (如: 1.0.0)")
                            return
                    elif attribute == "is_online":
                        if value in ["1", "0"]:
                            self.assistants[i].set_online(bool(int(value)))
                        else:
                            print("❌ 在线状态应为 1(在线) 或 0(离线)")
                            return
                    elif attribute == "score":
                        score_value = int(value)
                        if 0 <= score_value <= 100:
                            self.assistants[i].set_score(score_value)
                        else:
                            print("❌ 能力评分应在0-100之间")
                            return
                    else:
                        print("❌ 不支持修改的属性")
                        return

                    print(f"✅ 助手【{id}】修改成功！")
                except ValueError:
                    print("❌ 数值格式错误")
                return

        print(f"❌ 未找到ID为 {id} 的助手")

    def delete_assistant(self):
        """删除AI助手（按ID）"""
        try:
            id = int(input("请输入要删除的AI助手ID: "))

            for i in range(len(self.assistants)):
                if self.assistants[i] is not None and self.assistants[i].get_id() == id:
                    name = self.assistants[i].get_name()
                    self.assistants[i] = None
                    print(f"✅ 助手【{name}】已删除。")
                    return

            print(f"❌ 未找到ID为 {id} 的助手")
        except ValueError:
            print("❌ ID格式错误，请输入数字")

    def start_assistant(self):
        """启动AI助手服务"""
        try:
            id = int(input("请输入要启动的AI助手ID: "))

            for i in range(len(self.assistants)):
                if self.assistants[i] is not None and self.assistants[i].get_id() == id:
                    if self.assistants[i].is_online_status():
                        print(f"助手【{self.assistants[i].get_name()}】已在运行。")
                    else:
                        self.assistants[i].set_online(True)
                        print(f"✅ 助手【{self.assistants[i].get_name()}】已启动。")
                    return

            print(f"❌ 未找到ID为 {id} 的助手")
        except ValueError:
            print("❌ ID格式错误，请输入数字")

    def stop_assistant(self):
        """停止AI助手服务"""
        try:
            id = int(input("请输入要停止的AI助手ID: "))

            for i in range(len(self.assistants)):
                if self.assistants[i] is not None and self.assistants[i].get_id() == id:
                    if not self.assistants[i].is_online_status():
                        print(f"助手【{self.assistants[i].get_name()}】已停止。")
                    else:
                        self.assistants[i].set_online(False)
                        print(f"✅ 助手【{self.assistants[i].get_name()}】已停止。")
                    return

            print(f"❌ 未找到ID为 {id} 的助手")
        except ValueError:
            print("❌ ID格式错误，请输入数字")

    def assign_task(self):
        """为AI助手分配任务"""
        try:
            id = int(input("请输入目标AI助手ID: "))
            task = input("请输入任务内容: ")

            for i in range(len(self.assistants)):
                if self.assistants[i] is not None and self.assistants[i].get_id() == id:
                    if self.assistants[i].is_online_status():
                        print(f"✅ 任务已发送给 {self.assistants[i].get_name()} 处理: {task}")
                    else:
                        print(f"❌ {self.assistants[i].get_name()} 当前离线，无法执行任务。")
                    return

            print(f"❌ 未找到ID为 {id} 的助手")
        except ValueError:
            print("❌ ID格式错误，请输入数字")

    def show_statistics(self):
        """显示系统统计信息"""
        total = 0
        online = 0
        offline = 0
        score_sum = 0

        for assistant in self.assistants:
            if assistant is not None:
                total += 1
                if assistant.is_online_status():
                    online += 1
                else:
                    offline += 1
                score_sum += assistant.get_score()

        # 避免除零错误
        average_score = score_sum / total if total > 0 else 0

        print("\n系统统计信息：")
        print(f"总助手数: {total}")
        print(f"在线助手数: {online}")
        print(f"离线助手数: {offline}")
        print(f"平均能力评分: {average_score:.2f}")


# 主程序入口
if __name__ == "__main__":
    manager = AIManager()
    manager.menu()
